<template>
  <div class="project-detail-container">
    <div class="project-detail" v-loading="loading">
      <el-page-header 
        @click="goback"
        :icon="ArrowLeft"
        class="page-header"
      >
        <template #content>
          <span class="page-title">项目详情</span>
        </template>
      </el-page-header>

      <el-card class="detail-card">
        <div class="title-section">
          <h1>{{ project.name }}</h1>
          <el-button
            class="wechat-button"
            type="success"
            @click="showQRCode"
          >
            <el-icon><ChatRound /></el-icon>
            加我微信
          </el-button>
        </div>
        <div class="tech-stack-container">
          <el-tag 
            v-for="tech in project.techStack?.split(',')" 
            :key="tech" 
            class="tech-tag"
            type="success"
            size="large"
          >
            {{ tech.trim() }}
          </el-tag>
        </div>

        <!-- Description Section -->
        <div class="description">
          <h2>项目描述</h2>
          <p>{{ project.description }}</p>
        </div>

        <!-- Project Info Section -->
        <el-descriptions :column="2" border class="info-section">
          <el-descriptions-item label="项目价格">
            <span class="price">¥{{ project.price }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="浏览次数">
            <el-icon><View /></el-icon> {{ project.viewCount }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ project.createTime }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ project.updateTime }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- Video Section -->
        <div v-if="project.videoUrl" class="video-container">
          <video :src="project.videoUrl" controls class="project-video"></video>
        </div>

        <!-- Contact Info Section -->
        <div class="contact-info">
          <el-alert
            title="如有意向购买或者其他需求，请联系网站管理员，微信：793686633。"
            type="success"
            :closable="false"
            show-icon
          >
          </el-alert>
        </div>

        <!-- Action Buttons -->
        <div class="actions">
          <el-button type="primary" size="large" @click="handleDownload">
            <el-icon><Download /></el-icon> 下载项目
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- QR Code Dialog -->
    <el-dialog
      v-model="qrCodeVisible"
      title="微信二维码"
      width="300px"
      align-center
    >
      <div class="qr-code-container">
        <img src="../assets/wx.jpg" alt="WeChat QR Code" class="qr-code-img"/>
        <p>扫码加微信好友</p>
      </div>
    </el-dialog>

    <!-- Password Dialog -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="项目下载验证"
      width="400px"
      align-center
      :show-close="true"
      destroy-on-close
      @close="handleDialogClose"
    >
      <div class="password-container">
        <el-icon size="large" class="lock-icon"><Lock /></el-icon>
        <h3 class="dialog-subtitle">请输入下载密码</h3>
        <el-input
          v-model="password"
          type="password"
          placeholder="请输入密码"
          class="password-input"
          :prefix-icon="Key"
          @keyup.enter="confirmDownload"
        ></el-input>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="confirmDownload" :loading="downloadLoading">
            确认下载
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getProjectById } from '../api/project'
import { downloadFile } from '../api/file'
import { ElMessage } from 'element-plus'
import { View, Download, ChatRound, ArrowLeft, Lock, Key, Warning } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const downloadLoading = ref(false)
const project = ref({})
const qrCodeVisible = ref(false)
const passwordDialogVisible = ref(false)
const password = ref('')

const goback = () => {
  router.push("/project")
}
const fetchProjectDetail = async () => {
  loading.value = true
  try {
    const response = await getProjectById(route.params.id)
    project.value = response.data
  } catch (error) {
    ElMessage.error('获取项目详情失败')
  } finally {
    loading.value = false
  }
}

const handleDownload = () => {
  passwordDialogVisible.value = true
}

const confirmDownload = () => {
  if (!password.value) {
    ElMessage.warning('请输入密码')
    return
  }
  
  downloadLoading.value = true
  downloadFile(2, project.value.fileName, password.value).then(res => {
    downloadLoading.value = false
    if (res.type === "application/json") {
      // 如果返回的是JSON，说明可能是错误信息
      console.log("Error response:", res.text());
      
      res.text().then(jsonText => {
        const errorData = JSON.parse(jsonText);
        ElMessage.error(errorData.msg || '密码验证失败');
      });
    } else {
      // 正常的文件下载
      const url = URL.createObjectURL(res);
      const a = document.createElement('a');
      a.href = url;
      a.download = project.value.fileName;
      document.body.appendChild(a);
      a.click();
      URL.revokeObjectURL(url);
      document.body.removeChild(a);
      passwordDialogVisible.value = false;
      ElMessage.success('下载成功');
    }
  }).catch(error => {
    downloadLoading.value = false
    ElMessage.error('下载失败');
  });
};

const handleDialogClose = () => {
  password.value = ''
}

const handleCancel = () => {
  passwordDialogVisible.value = false
  handleDialogClose()
}

const showQRCode = () => {
  qrCodeVisible.value = true
}

onMounted(() => {
  fetchProjectDetail()
})
</script>

<style scoped>
.project-detail-container {
  width: 100%;
}

.project-detail {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
  background: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  cursor: pointer;
  position: relative;
  z-index: 2;
}

.page-header :deep(.el-page-header__back) {
  cursor: pointer;
  padding: 10px;
  margin: -10px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
}

.detail-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  flex: 1;
}

.title-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-section h1 {
  margin: 0;
  font-size: 28px;
  color: #303133;
}

.tech-stack-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.tech-tag {
  margin-right: 5px;
}

.media-section {
  margin: 15px 0;
}

.video-container {
  margin: 15px 0;
}

.project-video {
  width: 100%;
  max-height: 600px;
  border-radius: 8px;
}

.info-section {
  margin: 25px 0;
}

.price {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
}

.contact-info {
  margin: 25px 0;
}

.description {
  margin: 15px 0;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.description h2 {
  margin-bottom: 15px;
  font-size: 20px;
  color: #303133;
}

.description p {
  line-height: 1.6;
  color: #606266;
}

.actions {
  margin-top: 30px;
  text-align: center;
}

.actions .el-button {
  padding: 12px 24px;
  font-size: 16px;
  transition: all 0.3s;
}

.actions .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.wechat-tip {
  display: inline-block;
  margin-left: 10px;
  cursor: pointer;
  transition: transform 0.2s;
}

.wechat-tip:hover {
  transform: scale(1.05);
}

.qr-code-container {
  text-align: center;
}

.qr-code-img {
  width: 200px;
  height: 200px;
  object-fit: contain;
}

.qr-code-container p {
  margin-top: 10px;
  color: #606266;
}

.wechat-button {
  white-space: nowrap;
}

.password-container {
  text-align: center;
  padding: 10px 20px;
}

.password-input {
  margin: 20px 0;
}

.lock-icon {
  font-size: 48px;
  color: #409EFF;
  background: #ecf5ff;
  padding: 15px;
  border-radius: 50%;
  margin-bottom: 10px;
}

.dialog-subtitle {
  color: #606266;
  font-weight: 500;
  margin: 10px 0;
}

.error-message {
  color: #f56c6c;
  margin-top: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  background-color: #fef0f0;
  padding: 8px;
  border-radius: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 15px;
}

@media (max-width: 768px) {
  .project-detail {
    padding: 10px;
  }
  
  .title-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .wechat-button {
    align-self: flex-end;
  }
  
  .description {
    padding: 10px;
  }
  
  
}
</style>
